﻿using System;
using System.Collections;
using System.Windows.Controls;
using PSE.Deployment.ConfigurationManager.Controls.Validations;
using PSE.Deployment.SetupBase.Configuration;

namespace PSE.Deployment.ConfigurationManager.Controls
{
	/// <summary>
	/// UserControl que instancia um ComboBox pronto para Binding
	/// </summary>
	public class SimpleComboBox : ComboBox
	{
		XmlTag _tag = null;

		bool _isRequired;
		public bool IsRequired
		{
			get { return _isRequired; }
			set { _isRequired = value; }
		}

		public virtual bool IsValid
		{
			get { return this.Validate(); }
		}

		private SimpleComboBox()
		{
			this.SelectionChanged += new SelectionChangedEventHandler(SimpleComboBox_SelectionChanged);
			this.SetResourceReference(SimpleComboBox.StyleProperty, "ConfigurationSimpleTextBoxStyle");
		}

		void SimpleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (_tag != null && this.SelectedValue != null)
			{
				_tag.Value = this.SelectedValue.ToString();
				this.SetStyle(true);
			}
		}

		public SimpleComboBox(XmlTag tag, IEnumerable itemsSource, string displayMemberPath, string selectedValuePath, string selectedValue)
			: this()
		{
			_tag = tag;
			this.IsRequired = tag.IsRequired;

			if (itemsSource != null)
			{
				this.ItemsSource = itemsSource;
				this.DisplayMemberPath = displayMemberPath;
				this.SelectedValuePath = selectedValuePath;

				if (!String.IsNullOrEmpty(selectedValue))
					this.SelectedValue = selectedValue;
			}
		}

		bool Validate()
		{
			if (this.IsRequired && this.SelectedValue == null)
			{
				this.SetStyle(false);
				return false;
			}
			else
			{
				this.SetStyle(true);
				return true;
			}
		}

		void SetStyle(bool isValid)
		{
			if (isValid)
			{
				this.SetResourceReference(BaseSimpleTextBox.StyleProperty, "ConfigurationSimpleTextBoxStyle");
				this.ToolTip = null;
			}
			else
			{
				this.SetResourceReference(SimpleComboBox.StyleProperty, "ConfigurationErrorSimpleTextBoxStyle");
				this.ToolTip = SpecializedControlsValidations.GetDescription(ErrorMessage.RequiredField);
			}
		}
	}
}